<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="800px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-tabs v-model="activeTab" type="card">
        <!-- 内容 Tab -->
        <el-tab-pane label="内容" name="content">
          <el-form-item prop="content" label="">
            <Editor v-model="formData.content" height="300px" />
          </el-form-item>
        </el-tab-pane>

        <!-- 示例代码 Tab -->
        <el-tab-pane label="示例代码" name="democode">
          <el-form-item prop="democode" label="">
            <MonacoEditor
              v-model:value="formData.democode"
              language="cpp"
              theme="vs"
              :options="{
                minimap: { enabled: false },
                lineNumbers: 'on',
                tabSize: 2,
                automaticLayout: true,
                fontSize: 14,
                scrollBeyondLastLine: false
              }"
              style="height: 350px; width: 100%;"
              @change="handleCodeChange"
            />
          </el-form-item>
          <el-row justify="end" class="mt-2">
            <el-button type="primary" @click="handleOnlineRun">在线运行</el-button>
          </el-row>
        </el-tab-pane>

        <!-- 其他信息 Tab -->
        <el-tab-pane label="其他信息" name="metadata">
          <div class="metadata-form">
            <el-form-item label="所属URL" prop="url">
              <el-input v-model="formData.url" placeholder="请输入所属URL" />
            </el-form-item>
            <el-form-item label="所属类名" prop="cppClass">
              <el-input v-model="formData.cppClass" placeholder="请输入所属类名" />
            </el-form-item>
            <el-form-item label="API ID" prop="apiId">
              <el-input v-model="formData.apiId" placeholder="请输入API ID" maxlength="36" show-word-limit />
            </el-form-item>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DocplusApi, DocplusVO } from '@/api/plus/docplus'
import { Dialog } from '@/components/Dialog'
import MonacoEditor from 'monaco-editor-vue3'

/** 文档附加 表单 */
defineOptions({ name: 'DocplusForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const activeTab = ref('content') // 当前活动的Tab页

const formData = ref({
  id: undefined,
  content: undefined,
  democode: undefined,
  url: undefined,
  cppClass: undefined,
  apiId: undefined
})
const formRules = reactive({
  apiId: [
    { max: 36, message: 'API ID长度不能超过36个字符', trigger: 'blur' }
  ]
})
const formRef = ref() // 表单 Ref

// 处理代码变更
const handleCodeChange = (newValue: string) => {
  if (formData.value) {
    formData.value.democode = newValue as any
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: string) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 默认显示内容Tab
  activeTab.value = 'content'
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DocplusApi.getDocplus(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as DocplusVO
    if (formType.value === 'create') {
      await DocplusApi.createDocplus(data)
      message.success(t('common.createSuccess'))
    } else {
      await DocplusApi.updateDocplus(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    content: undefined,
    democode: undefined,
    url: undefined,
    cppClass: undefined,
    apiId: undefined
  }
  formRef.value?.resetFields()
}

// 在线运行按钮点击
const handleOnlineRun = () => {
  const apiid = formData.value.apiId || ''
  if (!apiid) {
    message.warning('请先填写 API ID')
    return
  }
  const host = location.origin
  const url = `${host}/dochtml/js/editplus.html?apiid=${encodeURIComponent(apiid)}&tab=code&model=edit`
  window.open(url, '_blank')
}
</script>

<style scoped>
/* 确保其他信息Tab中的表单项有合适的间距 */
:deep(.el-form-item) {
  margin-bottom: 22px;
}

/* 修复Tab页内容区域的高度 */
:deep(.el-tabs__content) {
  height: calc(100% - 40px);
  overflow: auto;
}

/* 确保Monaco编辑器在表单中的正确显示 */
:deep(.monaco-editor) {
  border-radius: 4px;
  overflow: hidden;
}

/* 确保元数据表单中的标签正确显示 */
.metadata-form :deep(.el-form-item__label) {
  width: 100px;
  text-align: right;
  padding-right: 12px;
  font-weight: normal;
  display: inline-block;
}
</style>